﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using BSF.BaseService.MonitorPlatform.Model;
using BSF.Db;

namespace BSF.Tool
{
    public class CommonHelper
    {
        private static volatile CommonHelper _instance = null;
        private static readonly object LockObject = new object();

        /// <summary>
        /// 创建实例
        /// </summary>
        /// <returns></returns>
        public static CommonHelper Instance()
        {
            if (_instance == null)
            {
                lock (LockObject)
                {
                    if (_instance == null)
                    {
                        _instance = new CommonHelper();
                    }
                }
            }
            return _instance;
        }

        private CommonHelper() { }

        /// <summary>
        /// 验证是否是限流控制器
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="action">方法,可能会直接外面拼接好之后通过该参数传进来</param>
        /// <param name="rule">限流的接口,多个用","隔开</param>
        /// <returns></returns>
        public static bool ValidateRestrictorController(string controller, string action, string rule)
        {
            if (string.IsNullOrWhiteSpace(controller) || string.IsNullOrWhiteSpace(action) || string.IsNullOrWhiteSpace(rule))
            {
                return false;
            }
            controller = controller.ToLower();
            action = action.ToLower();
            rule = rule.ToLower();
            if (rule.IndexOf(controller + "/" + action) == -1 || rule.IndexOf(action) == -1)
            {
                return false;
            }

            //if (controller == "goods" && action == "getshopcateandgood")
            //{
            //    return true;
            //}
            return true;
        }

        /// <summary>
        /// 是否是灰度验证用户
        /// </summary>
        /// <param name="abTestCustomerIDs"></param>
        /// <param name="token"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public static bool ValidateAbTestCustomer(string abTestCustomerIDs, string token, System.Web.HttpRequest request)
        {
            //TODO 测试用户
            //if (string.IsNullOrWhiteSpace(token) || string.IsNullOrWhiteSpace(abTestCustomerIDs) || request == null)
            //{
            //    return false;
            //}
            //var tokenObj = Dyd.Core.OAuth.Pub.GetAuthToken(request);
            //if (tokenObj == null)
            //{
            //    return false;
            //}
            //if (abTestCustomerIDs.IndexOf(tokenObj.userid) == -1)
            //{
            //    return false;
            //}
            return true;

        }

        /// <summary>
        /// 是否灰度验证商户账户
        /// </summary>
        /// <param name="abTestBusinessIDs"></param>
        /// <param name="businessID"></param>
        /// <returns></returns>
        public static bool ValidateAbTestBusiness(string abTestBusinessIDs, string businessID)
        {
            if (string.IsNullOrWhiteSpace(abTestBusinessIDs) || string.IsNullOrWhiteSpace(businessID))
            {
                return false;
            }
            if (abTestBusinessIDs.IndexOf(businessID) == -1)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取一个类指定的属性值
        /// </summary>
        /// <param name="info">object对象</param>
        /// <param name="field">属性名称</param>
        /// <returns></returns>
        public static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);
        }
        /// <summary>
        /// C#利用反射获取对象属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="propertyname"></param>
        /// <returns></returns>
        public static string GetObjectPropertyValue<T>(T t, string propertyname)
        {
            Type type = typeof(T);
            System.Reflection.PropertyInfo property = type.GetProperty(propertyname);
            if (property == null) return string.Empty;
            object o = property.GetValue(t, null);
            if (o == null) return string.Empty;
            return o.ToString();
        }

        /// <summary>
        /// 判断经纬度是否在销售范围里
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <param name="xsfw"></param>
        /// <returns></returns>
        public static bool PtInSxfw(decimal lng, decimal lat, string xsfw)
        {
            if (string.IsNullOrWhiteSpace(xsfw) || lat == 0 || lng == 0)
            {
                //销售范围为空，无效经纬度 直接返回
                return false;
            }
            List<string> mapArry = xsfw.Split(';').ToList();
            //第一个经纬度 填充到最后一个 形成闭环
            //  mapArry.Add(mapArry[0]);
            int i = 0;
            int j = mapArry.Count - 1;
            bool oddNodes = false;
            for (i = 0; i < mapArry.Count; i++)
            {
                string[] iArry = mapArry[i].Split(',');
                string[] jArry = mapArry[j].Split(',');
                if (iArry.Length < 2 || jArry.Length < 2)
                {
                    //经纬度格式非法 
                    return false;
                }
                decimal iX = LibConvert.StrToDecimal(iArry[0]);
                decimal iY = LibConvert.StrToDecimal(iArry[1]);

                decimal jX = LibConvert.StrToDecimal(jArry[0]);
                decimal jY = LibConvert.StrToDecimal(jArry[1]);
                if (((iY < lat && jY >= lat) || (jY < lat && iY >= lat)) && (iX <= lng || jX <= lng))
                {
                    if (iX + (lat - iY) / (jY - iY) * (jX - iX) < lng)
                    {
                        oddNodes = !oddNodes;
                    }
                }
                j = i;
            }
            return oddNodes;
        }

        /// <summary>
        /// 计算距离
        /// </summary>
        /// <param name="startLng">经度：120.096628</param>
        /// <param name="startLat">纬度：30.302800</param>
        /// <returns></returns>
        //public static double GetDistance(double startLng, double startLat, double endLng, double endLat)
        //{
        //    double earthRadius = 6378.137;
        //    double radLatBegin = startLat * Math.PI / 180.0;
        //    double radLatEnd = endLat * Math.PI / 180.0;
        //    double radLatDiff = startLat - endLat;
        //    double radLngDiff = startLng * Math.PI / 180.0 - endLng * Math.PI / 180.0;
        //    double distance = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(radLatDiff / 2), 2) + 
        //        Math.Cos(radLatBegin) * Math.Cos(radLatEnd) * Math.Pow(Math.Sin(radLngDiff / 2), 2)));
        //    distance = distance * earthRadius * 1000;
        //    return distance;
        //}

        private const double EarthRadius = 6378.137;//地球半径
        private static double Rad(double d)
        {
            return d * Math.PI / 180.0;
        }
        /// <summary>
        /// 计算距离
        /// </summary>
        /// <param name="lng1">经度：120.096628</param>
        /// <param name="lat1">纬度：30.302800</param>
        /// <returns></returns>
        public static double GetDistance(double lng1, double lat1, double lng2, double lat2)
        {
            double radLat1 = Rad(lat1);
            double radLat2 = Rad(lat2);
            double radLatDiff = radLat1 - radLat2;
            double radLngDiff = Rad(lng1) - Rad(lng2);
            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(radLatDiff / 2), 2) +
                Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(radLngDiff / 2), 2)));
            s = s * EarthRadius;
            s = Math.Round(s * 10000) / 10000;
            return s;
        }
        /// <summary>
        /// 计算距离
        /// </summary>
        /// <param name="lng1">经度：120.096628</param>
        /// <param name="lat1">纬度：30.302800</param>
        /// <returns></returns>
        public static double DistanceOfTwoPoints(double lng1, double lat1, double lng2, double lat2, GaussSphere gs = GaussSphere.Beijing54)
        {
            double radLat1 = Rad(lat1);
            double radLat2 = Rad(lat2);
            double a = radLat1 - radLat2;
            double b = Rad(lng1) - Rad(lng2);
            double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) +
             Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
            s = s * (gs == GaussSphere.WGS84 ? 6378137.0 : (gs == GaussSphere.Xian80 ? 6378140.0 : 6378245.0));
            s = Math.Round(s * 10000) / 10000;
            return s;
        }

        /// <summary>
        /// 高斯投影中所选用的参考椭球
        /// </summary>
        public enum GaussSphere
        {
            Beijing54,
            Xian80,
            WGS84,
        }

        //1.判断远程文件是否存在
        ///fileUrl:远程文件路径，包括IP地址以及详细的路径
        protected static bool RemoteFileExists(string fileUrl)
        {
            bool result = false;//下载结果
            WebResponse response = null;
            try
            {
                WebRequest req = WebRequest.Create(fileUrl);
                response = req.GetResponse();
                result = response == null ? false : true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return result;
        }

        #region 微信相关

        /// <summary>SHA1加密</summary>
        /// <remarks>
        /// sha1校验工具
        /// http://tool.oschina.net/encrypt?type=2
        /// </remarks>
        /// <param name="str">需要加密的字符串</param>
        /// <returns></returns>
        public static string EncryptSHA1(string str)
        {

            StringBuilder _result = new StringBuilder();
            System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create();
            byte[] sha1Arr = sha1.ComputeHash(Encoding.UTF8.GetBytes(str));

            foreach (var b in sha1Arr)
            {
                _result.AppendFormat("{0:x2}", b);
            }
            return _result.ToString();
        }

        /// <summary>
        /// 微信公众平台SHA1哈希加密算法  
        /// </summary>
        /// <param name="str_sha1_in"></param>
        /// <returns></returns>
        public static string SHA1_Hash(string str_sha1_in)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str_sha1_in);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
            str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
            return str_sha1_out;
        }

        public static string SHA1Sign(string data)
        {
            byte[] temp1 = Encoding.UTF8.GetBytes(data);

            SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
            byte[] temp2 = sha.ComputeHash(temp1);
            sha.Clear();

            // 注意， 不能用这个
            //string output = Convert.ToBase64String(temp2);

            string output = BitConverter.ToString(temp2);
            output = output.Replace("-", "");
            output = output.ToLower();
            return output;
        }

        /// <summary>
        /// 获取时间戳  使用协调世界时UTC减去1970年1月1日
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long GetTimeStamp(DateTime dateTime)
        {
            return (long)(dateTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
            //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1);
            //return Convert.ToUInt32(ts.TotalSeconds);
        }

        /// <summary>
        /// 将数据库中timespan转换成十六进制字符串
        /// </summary>
        /// <param name="objTs">从数据库中获取的timespan值</param>      
        /// <returns>timespan十六进制字符串</returns>
        public string ConvertToTimeSpanString(object objTs)
        {
            byte[] btTsArray = objTs as byte[];
            string strTimeSpan = "0x" + BitConverter.ToString(btTsArray).Replace("-", "");
            return strTimeSpan;
        }

        public static int DateTimeToInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        public static DateTime IntToDateTime(int Seconds)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return startTime.AddSeconds(Seconds);
        }
        public static Int64 UnixInter()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            return Convert.ToInt64(Math.Floor(ts.TotalSeconds));
        }

        readonly static DateTime START_TIME = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式精确到17位。
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long GetTimeTicks(DateTime time)
        {
            return (time - START_TIME).Ticks;
        }

        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式精确到10位。
        /// 
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long GetUnixTime(DateTime time)
        {
            return (long)(time - START_TIME).TotalSeconds;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string RandomString()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            Random rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }
        #endregion

        #region ip

        public static System.Web.HttpRequest GetRequest()
        {
            System.Web.HttpRequest req = null;

            if (System.Web.HttpContext.Current != null)//当前请求
                req = System.Web.HttpContext.Current.Request;
            else
                req = null;
            return req;
        }

        /// <summary>
        /// 耗时参数绑定
        /// </summary>
        /// <param name="req">请求</param>
        /// <param name="paramBinds"></param>
        public static void ParamBinds(System.Web.HttpRequest req, ref BindParameter paramBinds)//ref ParamBinds paramBinds
        {
            Type entitytype = paramBinds.GetType();//BindParameter类型
            PropertyInfo[] entityProperties = entitytype.GetProperties();
            //循环BindParameter属性取值
            foreach (var entityProperty in entityProperties)
            {
                //var obj = req.QueryString[entityProperty.Name.ToLower()] as string;
                //if (string.IsNullOrWhiteSpace(obj))
                //{
                //    obj = req.Form[entityProperty.Name.ToLower()] as string;
                //}
                var obj = req[entityProperty.Name.ToLower()] as string;

                entityProperty.SetValue(paramBinds, obj, null);
            }

            var header = req.Headers;
            List<string> withParam = new List<string>
            {
                "authorization"
            };
            foreach (var key in header.AllKeys)
            {
                if (!withParam.Contains(key.ToLower()))
                    continue;
                paramBinds.Token = header.GetValues(key).First().ToString();
            }

            //if (req.Url != null) 
            paramBinds.Ip = GetIP(req);
        }

        /// <summary>
        /// 获取客户端ip
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public static string GetIP(System.Web.HttpRequest request)
        {
            /*
             * 1. 在ASP.NET中专用属性：
      　　    获取服务器电脑名：Page.Server.ManchineName
      　　    获取用户信息：Page.User
      　　    获取客户端电脑名：Page.Request.UserHostName
      　　    获取客户端电脑IP：Page.Request.UserHostAddress
      　　    2. 在网络编程中的通用方法：
      　　    获取当前电脑名：static System.Net.Dns.GetHostName()
      　　    根据电脑名取出全部IP地址：static System.Net.Dns.Resolve(电脑名).AddressList
      　　    也可根据IP地址取出电脑名：static System.Net.Dns.Resolve(IP地址).HostName
      　　    3. 系统环境类的通用属性：
      　　    当前电脑名：static System.Environment.MachineName
      　　    当前电脑所属网域：static System.Environment.UserDomainName
      　　    当前电脑用户：static System.Environment.UserName 
             * **/
            //string ip = string.Empty;
            //try
            //{
            //    if (!string.IsNullOrEmpty(req.ServerVariables["HTTP_VIA"]))
            //        ip = Convert.ToString(req.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            //}
            //catch { }
            //if (string.IsNullOrEmpty(ip))
            //    ip = Convert.ToString(req.ServerVariables["REMOTE_ADDR"]);
            //return ip;
            try
            {
                var userHostAddress = request.UserHostAddress;

                // Attempt to parse.  If it fails, we catch below and return "0.0.0.0"
                // Could use TryParse instead, but I wanted to catch all exceptions
                IPAddress.Parse(userHostAddress);

                var xForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
                if (string.IsNullOrEmpty(xForwardedFor))
                {
                    xForwardedFor = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }

                if (string.IsNullOrEmpty(xForwardedFor))
                    return userHostAddress;

                // Get a list of public ip addresses in the X_FORWARDED_FOR variable
                var publicForwardingIps = xForwardedFor.Split(',').Where(ip => !IsPrivateIpAddress(ip)).ToList();

                // If we found any, return the last one, otherwise return the user host address
                return publicForwardingIps.Any() ? publicForwardingIps.Last() : userHostAddress;
            }
            catch (Exception)
            {
                // Always return all zeroes for any failure (my calling code expects it)
                return "0.0.0.0";
            }
        }

        private static bool IsPrivateIpAddress(string ipAddress)
        {
            // http://en.wikipedia.org/wiki/Private_network
            // Private IP Addresses are: 
            //  24-bit block: 10.0.0.0 through 10.255.255.255
            //  20-bit block: 172.16.0.0 through 172.31.255.255
            //  16-bit block: 192.168.0.0 through 192.168.255.255
            //  Link-local addresses: 169.254.0.0 through 169.254.255.255 (http://en.wikipedia.org/wiki/Link-local_address)

            var ip = IPAddress.Parse(ipAddress);
            var octets = ip.GetAddressBytes();

            var is24BitBlock = octets[0] == 10;
            if (is24BitBlock) return true; // Return to prevent further processing

            var is20BitBlock = octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31;
            if (is20BitBlock) return true; // Return to prevent further processing

            var is16BitBlock = octets[0] == 192 && octets[1] == 168;
            if (is16BitBlock) return true; // Return to prevent further processing

            var isLinkLocalAddress = octets[0] == 169 && octets[1] == 254;
            return isLinkLocalAddress;
        }

        public static bool PingSuccess(string address)
        {
            Ping ping = null;
            try
            {
                ping = new Ping();
                var pingReply = ping.Send(address, 120);//第一个参数为ip地址，第二个参数为ping的时间(等待 ICMP 回送答复消息的最大毫秒数)
                if (pingReply == null)
                    return false;

                return pingReply.Status == IPStatus.Success;
            }
            finally
            {
                if (ping != null)
                {
                    // 2.0 下ping 的一个bug，需要显示转型后释放
                    //IDisposable disposable = ping;
                    //disposable.Dispose();
                    ping.Dispose();
                }
            }
        }
        /// <summary>
        /// c# 判断字符串是否为IP地址，验证IP
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsCorrectIP(string ip)
        {
            //return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
            Match m = Regex.Match(ip, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");
            //var str = Regex.Replace(ip, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}", "10.0.13.6");
            if (m.Success)
            {
                return true;
            }
            return false;
        }
        //判断IP地址是否有效
        public static bool IsRightIP(string ip)
        {
            if (Regex.IsMatch(ip, "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4 || ips.Length == 6)
                {
                    if (System.Int32.Parse(ips[0]) < 256 && System.Int32.Parse(ips[1]) < 256 & System.Int32.Parse(ips[2]) < 256 & System.Int32.Parse(ips[3]) < 256)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            else
                return false;
        }

        public static string ClientIp()
        {
            string result = "";
            if (System.Web.HttpContext.Current != null)
            {
                HttpRequest request = HttpContext.Current.Request;
                #region 获取IP
                string userIP = string.Empty;
                try
                {
                    if (request.ServerVariables["HTTP_X_FORWARDED_FOR"] != "")
                        userIP = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    else
                        userIP = request.ServerVariables["REMOTE_ADm"];
                }
                catch
                {
                    userIP = Convert.ToString(request.ServerVariables["REMOTE_ADDR"]);
                }

                if (string.IsNullOrEmpty(userIP))
                    userIP = request.UserHostAddress;
                result = userIP;
                #endregion
                #region
                //result = request.ServerVariables["REMOTE_ADDR"];
                //if (string.IsNullOrEmpty(result))
                //{
                //    result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                //}
                //if (string.IsNullOrEmpty(result))
                //{
                //    result = request.ServerVariables["HTTP_CLIENT_IP"];
                //}
                //if (string.IsNullOrEmpty(result))
                //{
                //    result = request.UserHostAddress;
                //}

                //if (string.IsNullOrEmpty(result))
                //{
                //    return string.Empty;
                //}
                #endregion

                return result;
            }
            return result;
        }

        /// <summary>
        /// 获取服务器IP
        /// </summary>
        /// <returns></returns>
        public static string GetServerIP()
        {
            string str = "127.0.0.1";
            try
            {
                string hostName = Dns.GetHostName();
                var hostEntity = Dns.GetHostEntry(hostName);
                var ipAddressList = hostEntity.AddressList;
                var ipAddress = ipAddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);

                if (ipAddress != null)
                {
                    str = ipAddress.ToString();
                }
                return str;
            }
            catch (Exception) { str = string.Empty; }
            return str;
        }

        /// <summary>
        /// 将IPv4格式的字符串转换为int型表示
        /// </summary>
        /// <param name="strIPAddress">IPv4格式的字符</param>
        /// <returns></returns>
        public static long IPToNumber(string strIPAddress)
        {
            if (string.IsNullOrWhiteSpace(strIPAddress)) { return 0; }
            string[] arrayIP = strIPAddress.Split('.');
            long sip1 = long.Parse(arrayIP[0]);
            long sip2 = long.Parse(arrayIP[1]);
            long sip3 = long.Parse(arrayIP[2]);
            long sip4 = long.Parse(arrayIP[3]);

            return (sip1 << 24) + (sip2 << 16) + (sip3 << 8) + sip4;
        }

        #endregion

        /// <summary>
        /// 根据 Agent 判断是否是手机浏览器
        /// </summary>
        /// <returns></returns>
        public static bool CheckAgent()
        {
            bool flag = false;
            string agent = HttpContext.Current.Request.UserAgent;
            string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "UCBrowser" };
            //排除 Windows 桌面系统 ，主要标志字符串为Windows NT
            if (!agent.Contains("Windows NT") ||
                (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
            {
                //排除 苹果桌面系统 ,主要标志字符串为Macintosh
                if (!agent.Contains("Windows NT") && !agent.Contains("Macintosh"))
                {
                    foreach (string item in keywords)
                    {
                        if (agent.Contains(item))
                        //符合Android", "iPhone", "iPod", "iPad", "Windows Phone", "UCBrowser"的，返回true
                        {
                            flag = true;
                            break;
                        }
                    }
                }
            }
            return flag;
        }

        /// <summary>
        /// 得到给业务参数使用的地区编码 
        /// <param name="dqbm">地区编码</param>
        /// </summary>
        public static int GetDqbmForConfig(int? dqbm)
        {
            return GetDqbmForConfig(0, 0, dqbm);
        }

        /// <summary>
        /// 得到给业务参数使用的地区编码 
        /// </summary>
        /// <param name="longitude"></param>
        /// <param name="latitude"></param>
        /// <param name="dqbm"></param>
        /// <returns></returns>
        private static int GetDqbmForConfig(decimal? longitude, decimal? latitude, int? dqbm)
        {
            if (dqbm.HasValue)
            {
                if (dqbm > 100000)
                {
                    return LibConvert.StrToInt(dqbm.ToString().Substring(0, 4) + "00");
                }

                return 0;
            }
            else
            {
                if (!longitude.HasValue || !latitude.HasValue || longitude.Value == 0 || latitude.Value == 0)
                {
                    return 0;
                }
                //根据经纬度去表里获取地区编码
                return 0;//return Dyd.Core.OAuth.Pub.GetDqbm(longitude, latitude);
            }
        }

        /// <summary>
        /// 得到字符串的长度，一个汉字算2个字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetLength(string str)
        {
            if (str.Length == 0) return 0;

            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            byte[] s = ascii.GetBytes(str);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
            }
            return tempLen;
        }

    }
}
